package com.lw.mall.web.lw;


import com.lw.mall.entity.chat.UserChat;
import com.lw.mall.entity.pojo.ResultBean;
import com.lw.mall.service2.UserService2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Controller
public class ChatController {

    @Autowired
    private UserService2 userService2;
    //检查是否登录
    @GetMapping("/product/checkLogin")
    @ResponseBody
    public ResultBean checkLogin(HttpSession httpSession) throws Exception {
        final ResultBean<Object> resultBean = new ResultBean<>();
        final Object user = httpSession.getAttribute("user");
        if (user==null){
            //没有登录
            throw new Exception("未登录！登录后才可以与卖家交流");
        }else {
           return resultBean;
        }
    }

    //跳转到聊天页
    @GetMapping("/chartroom.html")
    public String chartRoomHtml(){
        return "mall/mai/chatroom";
    }

    //admin跳转到聊天页
    @GetMapping("/admin/chartroom.html")
    public String adminChartRoomHtml(Model model){
        model.addAttribute("admin",true);
        return "mall/mai/chatroom";
    }

    @RequestMapping("/onlineusers")
    @ResponseBody
    public Set<String> onlineusers(@RequestParam("currentuser") String currentuser) {
        ConcurrentHashMap<String, Session> map = WebSocketServer.getSessionPools();
        Set<String> set = map.keySet();
        Iterator<String> it = set.iterator();
        Set<String> nameset = new HashSet<String>();
        while (it.hasNext()) {
            String entry = it.next();
            if (!entry.equals(currentuser))
                nameset.add(entry);
        }
        return nameset;
    }

    //前端发送ajax 请求获取userName 和 userId
    @GetMapping("/currentuser")
    @ResponseBody
    public UserChat currentuser(HttpSession httpSession){
        Long uid = (Long)httpSession.getAttribute("uid");
        String name =userService2.getNameById(uid);
        return new UserChat(uid, name);
    }

    /**
     * 聊天室退出登录
     * @param request
     * @return
     */
    @GetMapping("/chat/logout")
    public String logout(HttpServletRequest request){
        request.getSession().removeAttribute("user");
        request.getSession().removeAttribute("uid");
        return "redirect:/";
    }
}
